using System;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class SliderHelper : NodeHelper
    {
        public AudioClip clip;
        public SoundType soundType;

        [SerializeField] private Slider _Slider;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey max;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey min;
        public bool isFixed;

        private Slider Slider
        {
            get
            {
                if (_Slider == null) _Slider = GetComponent<Slider>();

                return _Slider;
            }
        }

        public BindDataType dataType = BindDataType.Int;
        protected override BindDataType bindDataType => dataType;

        protected override void Start()
        {
            if (isFixed) return;
            Slider.onValueChanged.AddListener(ChangeSliderValue);
        }

        public override void SetData(JSONObject json)
        {
            base.SetData(json);
            if (!max.IsEmpty()) Slider.maxValue = max.Get(json).AsInt;
            if (!min.IsEmpty()) Slider.minValue = min.Get(json).AsInt;
        }

        protected override void BindData(int i)
        {
            Slider.value = i;
        }

        protected override void BindData(float i)
        {
            Slider.value = i;
        }

        public void ChangeSliderValue(float value)
        {
            if (dataType == BindDataType.Int)
            {
                Change((int)Math.Floor(value));
            }
            else
            {
                Change(value);
            }

            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);
        }
    }
}